import { createStore } from "vuex";
import { getMenuList, getUserInfo } from "@/api/login";
import router from '@/router/index'
import { transformMenuToRoutes } from '@/utils/routerUtils'

const userStore = createStore({
  state: () => {
    const state = sessionStorage.getItem("state");
    return state
      ? JSON.parse(state)
      : {
        userInfo: {
          id: null,
          username: "",
          nickName: "",
          profilePicture: "",
          address: "",
          email: "",
          phone: "",
        },
        menus: [],
        roles: [],
        permissions: [],
        token: "",
      };
  },
  mutations: {
    SET_USER_INFO(state) {
      getUserInfo().then((res) => {
        if (res.data.code == 200) {
          state.userInfo.id = res.data.data.id;
          state.userInfo.username = res.data.data.username;
          state.userInfo.nickName = res.data.data.nickName;
          state.userInfo.profilePicture = res.data.data.profilePicture;
          state.userInfo.address = res.data.data.address;
          state.userInfo.email = res.data.data.email;
          state.userInfo.phone = res.data.data.phone;
          state.roles = res.data.data.roles;
          state.permissions = res.data.data.permissions;
          sessionStorage.setItem("state", JSON.stringify(state));
        }
      });
    },
    SET_MENU_LIST(state) {
      getMenuList().then((res) => {
        if (res.data.code == 200) {
          state.menus = res.data.data;
          sessionStorage.setItem("state", JSON.stringify(state));

          // 将菜单转为路由并添加
          const routes = transformMenuToRoutes( state.menus )
          routes.forEach(route => {
            router.addRoute('Layout', route)
          })
        }
      });
    },
    SET_TOKEN(state, token) {
      state.token = token;
      sessionStorage.setItem("state", JSON.stringify(state));
    },
    REMOVE_USER_INFO(state) {
      state.userInfo = {
        id: null,
        username: "",
        nickName: "",
        profilePicture: "",
        address: "",
        email: "",
        phone: "",
      };
      state.menus = [];
      state.roles = [];
      state.permissions = [];
      sessionStorage.setItem("state", JSON.stringify(state));
    },
  },
  actions: {},
  modules: {},
});

export default userStore;
